<?php
/**
 * Created by PhpStorm.
 * User: Administratorjing
 * Date: 2018/3/29/029
 * Time: 13:04
 */

namespace app\api\controller\v1;
use app\api\controller\BaseController;
use app\api\model\UserAddress;
use app\api\validate\AddressNew;
use app\api\service\Token as TokenService;
use app\api\model\User as UserModel;
use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\SuccessMessage;
use app\lib\exception\TokenException;
use app\lib\exception\UserException;
use think\Controller;

class Address extends BaseController
{
    //前置方法，先执行这个前置方法再执行之后的
    protected $beforeActionList=[
       'checkPrimaryScope'=>['only'=>'createOrUpdateAddress,getUserAddress']
    ];
    public function getUserAddress(){
        $uid = TokenService::getCurrentUid();
        $userAddress = UserAddress::where('user_id',$uid)->find();
        if(!$userAddress){
            throw new UserException([
               'msg'  => '用户地址不存在',
               'errorCode'  => 60001
            ]);
        }
        return $userAddress;
    }
    public function createOrUpdateAddress()
    {
        $validate = new AddressNew();
        $validate->goCheck();
        //(new AddressNew())->goCheck();
        //根据token获取用户的uid
        //根据uid来查找用户数据，判断用户是否存在，如果不存在抛出异常
        //获取用户从客户端提交过来的信息
        //根据用户地址信息是否存在，从而判断是添加地址或是跟新地址
        $uid = TokenService::getCurrentUid();
        $user = UserModel::get($uid);
        if(!$user){
            throw new UserException();
        }
        //获取数据
        $dataArray = $validate->getDataByRule(input('post.'));
        $userAddress = $user->address;
        if(!$userAddress)
        {
            //创建
            $user->address()->save($dataArray);
        }else{
            //更新操作
            $user->address->save($dataArray);
        }
        //return $user;
        return json(new SuccessMessage(),201);
    }
}